<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG转图片工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
            min-height: 100vh;
        }
        .main-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            gap: 30px;
            min-height: calc(100vh - 40px);
        }
        .left-panel {
            flex: 1;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .right-panel {
            flex: 1;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin: 20px 0;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        .upload-area:hover {
            border-color: #007bff;
        }
        .upload-area.dragover {
            border-color: #007bff;
            background-color: #f8f9fa;
        }
        .file-input {
            display: none;
        }
        .btn {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .preview {
            margin: 20px 0;
            text-align: center;
        }
        .preview svg {
            max-width: 100%;
            max-height: 300px;
            border: 1px solid #ddd;
        }
        .options {
            margin: 20px 0;
        }
        .option-group {
            margin: 15px 0;
            display: flex;
            align-items: center;
        }
        label {
            display: inline-block;
            width: 80px;
            margin-right: 15px;
            font-weight: bold;
        }
        select, input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
            flex: 1;
            max-width: 200px;
        }
        .status {
            margin: 10px 0;
            padding: 10px;
            border-radius: 5px;
        }
        .status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .panel-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }
        .convert-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
            width: 100%;
        }
        .convert-btn:hover {
            background-color: #218838;
        }
        .convert-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        #help-content {
            margin-top: 30px;
            font-size: 12px;
        }
        #help-content h2 {
            margin-top: 25px;
            margin-bottom: 10px;
            font-size: 14px;
        }
        #help-content p {
            margin: 8px 0;
            line-height: 1.4;
            color: #666;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="main-container">
        <div class="left-panel">
            <h1>SVG转图片工具</h1>

                <div class="upload-area" id="uploadArea">
                <p>点击选择SVG文件或拖拽文件到此处</p>
                <input type="file" id="fileInput" class="file-input" accept=".svg,image/svg+xml">
                <button class="btn" onclick="document.getElementById('fileInput').click()">选择文件</button>
                    </div>

            <div id="preview" class="preview" style="display: none;">
                <h3>预览</h3>
                <div id="svgPreview"></div>
            </div>

            <div id="status"></div>
        </div>

        <div class="right-panel">
            <div class="options" id="options" style="display: none;">
                <h3 class="panel-title">转换选项</h3>
                <div class="option-group">
                    <label for="format">格式:</label>
                    <select id="format">
                        <option value="png">PNG</option>
                        <option value="jpeg">JPEG</option>
                    </select>
                </div>
                <div class="option-group">
                    <label for="scale">缩放:</label>
                    <input type="number" id="scale" value="1" min="0.1" max="10" step="0.1">
                </div>
                <div class="option-group">
                    <label for="width">宽度:</label>
                    <input type="number" id="width" placeholder="自动">
                        </div>
                <div class="option-group">
                    <label for="height">高度:</label>
                    <input type="number" id="height" placeholder="自动">
                </div>
                <button class="convert-btn" onclick="convertSvg()">转换并下载</button>
            </div>

            <div id="help-content">
                <h2 class="panel-title">使用说明</h2>
                <p>请将SVG文件拖拽到左侧的"上传区域"或点击"选择文件"按钮。</p>
                <p>支持SVG和SVG+XML格式。</p>

                <h2 class="panel-title">SVG预览</h2>
                <p>上传SVG文件后，您可以在左侧预览其内容。</p>
                <p>您可以调整缩放比例和尺寸，以确保图片符合您的需求。</p>

                <h2 class="panel-title">转换选项</h2>
                <p>在上方的"转换选项"区域，您可以设置图片的格式、缩放比例和尺寸。</p>
                <p>选择"PNG"或"JPEG"作为输出格式。</p>
                <p>缩放比例范围为0.1到10，您可以根据需要调整。</p>
                <p>如果您希望图片保持原始比例，请将宽度或高度设置为"自动"。</p>

                <h2 class="panel-title">转换结果</h2>
                <p>点击"转换并下载"按钮后，工具将自动生成图片并下载。</p>
                <p>您可以选择不同的格式和尺寸，以获得最佳的图片质量。</p>
            </div>
        </div>
    </div>

    <script>
        let currentSvg = null;
        let currentSvgElement = null;
        let uploadedFileName = null; // 保存上传的文件名

        // 文件选择处理
        document.getElementById('fileInput').addEventListener('change', handleFileSelect);
        
        // 拖拽处理
        const uploadArea = document.getElementById('uploadArea');
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFile(files[0]);
            }
        });

        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                handleFile(file);
            }
        }

        function handleFile(file) {
            if (!file.type.includes('svg')) {
                showStatus('请选择SVG文件', 'error');
                return;
            }

            // 保存文件名（去掉扩展名）
            const lastDotIndex = file.name.lastIndexOf('.');
            uploadedFileName = lastDotIndex > 0 ? file.name.substring(0, lastDotIndex) : file.name;

            const reader = new FileReader();
            reader.onload = function(e) {
                currentSvg = e.target.result;
                displayPreview(currentSvg);
                document.getElementById('options').style.display = 'block';
                showStatus('SVG文件加载成功', 'success');
            };
            reader.readAsText(file);
        }

        function displayPreview(svgContent) {
            const preview = document.getElementById('preview');
            const svgPreview = document.getElementById('svgPreview');
            
            // 创建SVG元素
            const div = document.createElement('div');
            div.innerHTML = svgContent;
            const svgElement = div.querySelector('svg');
            
            if (svgElement) {
                currentSvgElement = svgElement;
                svgPreview.innerHTML = '';
                svgPreview.appendChild(svgElement);
                preview.style.display = 'block';
                
                // 显示尺寸信息
                const sizeInfo = getSvgSizeInfo(svgElement);
                const sizeDiv = document.createElement('div');
                sizeDiv.style.marginTop = '10px';
                sizeDiv.style.fontSize = '12px';
                sizeDiv.style.color = '#666';
                sizeDiv.innerHTML = `原始尺寸: ${sizeInfo.width} x ${sizeInfo.height}`;
                svgPreview.appendChild(sizeDiv);
                
                // 自动填入初始尺寸
                setTimeout(() => {
                    updateDimensionsFromScale();
                }, 100);
            }
        }

        function getSvgSizeInfo(svgElement) {
            let width, height;
            
            // 首先尝试从viewBox获取尺寸
            const viewBox = svgElement.getAttribute('viewBox');
            if (viewBox) {
                const parts = viewBox.split(' ');
                width = parseFloat(parts[2]);
                height = parseFloat(parts[3]);
            } else {
                // 如果没有viewBox，尝试从width和height属性获取
                const widthAttr = svgElement.getAttribute('width');
                const heightAttr = svgElement.getAttribute('height');
                if (widthAttr && heightAttr) {
                    width = parseFloat(widthAttr);
                    height = parseFloat(heightAttr);
                } else {
                    // 如果都没有，使用渲染尺寸
                    const rect = svgElement.getBoundingClientRect();
                    width = Math.round(rect.width);
                    height = Math.round(rect.height);
                }
            }
            
            return { width, height };
        }

        function updateDimensionsFromScale() {
            if (!currentSvgElement) return;
            
            const scaleInput = document.getElementById('scale');
            if (!scaleInput) return;
            
            const scale = parseFloat(scaleInput.value);
            const sizeInfo = getSvgSizeInfo(currentSvgElement);
            
            const newWidth = Math.round(sizeInfo.width * scale);
            const newHeight = Math.round(sizeInfo.height * scale);
            
            const widthInput = document.getElementById('width');
            const heightInput = document.getElementById('height');
            
            if (widthInput) widthInput.value = newWidth;
            if (heightInput) heightInput.value = newHeight;
            
            // 检查尺寸限制并提示
            const maxDimension = 16384;
            if (newWidth > maxDimension || newHeight > maxDimension) {
                showStatus(`警告：当前缩放比例会导致尺寸过大 (${newWidth}x${newHeight})，建议降低缩放比例`, 'error');
            } else if (newWidth < 1 || newHeight < 1) {
                showStatus(`警告：当前缩放比例会导致尺寸过小 (${newWidth}x${newHeight})，建议提高缩放比例`, 'error');
            } else {
                // 清除之前的错误提示
                const status = document.getElementById('status');
                if (status && status.className.includes('error')) {
                    status.textContent = '';
                    status.className = 'status';
                }
            }
        }

        function convertSvg() {
            if (!currentSvgElement) {
                showStatus('请先选择SVG文件', 'error');
                return;
            }

            try {
                const format = document.getElementById('format').value;
                const scale = parseFloat(document.getElementById('scale').value);
                const userWidth = document.getElementById('width').value;
                const userHeight = document.getElementById('height').value;

                // 获取SVG的原始尺寸
                let originalWidth, originalHeight;
                
                // 首先尝试从viewBox获取尺寸
                const viewBox = currentSvgElement.getAttribute('viewBox');
                if (viewBox) {
                    const parts = viewBox.split(' ');
                    originalWidth = parseFloat(parts[2]);
                    originalHeight = parseFloat(parts[3]);
                } else {
                    // 如果没有viewBox，尝试从width和height属性获取
                    const widthAttr = currentSvgElement.getAttribute('width');
                    const heightAttr = currentSvgElement.getAttribute('height');
                    if (widthAttr && heightAttr) {
                        originalWidth = parseFloat(widthAttr);
                        originalHeight = parseFloat(heightAttr);
                    } else {
                        // 如果都没有，使用渲染尺寸
                        const rect = currentSvgElement.getBoundingClientRect();
                        originalWidth = rect.width;
                        originalHeight = rect.height;
                    }
                }

                // 计算最终尺寸，保持宽高比
                let finalWidth, finalHeight;
                
                if (userWidth && userHeight) {
                    // 用户指定了宽度和高度
                    finalWidth = parseInt(userWidth);
                    finalHeight = parseInt(userHeight);
                } else if (userWidth) {
                    // 只指定了宽度，按比例计算高度
                    finalWidth = parseInt(userWidth);
                    finalHeight = Math.round((originalHeight / originalWidth) * finalWidth);
                } else if (userHeight) {
                    // 只指定了高度，按比例计算宽度
                    finalHeight = parseInt(userHeight);
                    finalWidth = Math.round((originalWidth / originalHeight) * finalHeight);
                } else {
                    // 使用缩放比例
                    finalWidth = Math.round(originalWidth * scale);
                    finalHeight = Math.round(originalHeight * scale);
                }

                // 检查尺寸限制（浏览器通常限制为16384x16384）
                const maxDimension = 16384;
                if (finalWidth > maxDimension || finalHeight > maxDimension) {
                    showStatus(`尺寸过大！最大支持 ${maxDimension}x${maxDimension} 像素。当前尺寸: ${finalWidth}x${finalHeight}`, 'error');
                    return;
                }

                // 检查最小尺寸
                if (finalWidth < 1 || finalHeight < 1) {
                    showStatus('尺寸过小！请调整缩放比例或尺寸。', 'error');
                    return;
                }

                // 自动填充到输入框
                document.getElementById('width').value = finalWidth;
                document.getElementById('height').value = finalHeight;

                console.log('原始尺寸:', originalWidth, 'x', originalHeight);
                console.log('最终尺寸:', finalWidth, 'x', finalHeight);

                // 创建canvas
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');

                canvas.width = finalWidth;
                canvas.height = finalHeight;

                // 创建Image对象
                const img = new Image();
                
                // 将SVG转换为data URL，避免跨域问题
                const svgDataUrl = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(currentSvg)));
                
                img.onload = function() {
                    // 绘制到canvas，保持比例
                    ctx.drawImage(img, 0, 0, finalWidth, finalHeight);

                    // 转换为图片并下载
                    canvas.toBlob(function(blob) {
                        if (!blob) {
                            showStatus('转换失败：无法创建图片数据', 'error');
                            return;
                        }
                        
                        try {
                            const downloadUrl = URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = downloadUrl;
                            a.download = `${uploadedFileName || 'converted'}.${format}`;
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                            URL.revokeObjectURL(downloadUrl);
                            
                            showStatus(`转换完成，文件已下载 (${finalWidth}x${finalHeight})`, 'success');
                        } catch (error) {
                            showStatus('下载失败: ' + error.message, 'error');
                        }
                    }, `image/${format}`, 0.9);
                };

                img.onerror = function() {
                    showStatus('SVG加载失败，请检查文件格式', 'error');
                };

                img.src = svgDataUrl;

            } catch (error) {
                console.error('转换错误:', error);
                showStatus('转换失败: ' + error.message, 'error');
            }
        }

        // 添加输入框变化时的比例计算
        function updateDimensions() {
            if (!currentSvgElement) return;
            
            const sizeInfo = getSvgSizeInfo(currentSvgElement);
            const widthInput = document.getElementById('width');
            const heightInput = document.getElementById('height');
            
            if (!widthInput || !heightInput) return;
            
            // 如果只修改了宽度，自动计算高度
            if (widthInput.value && !heightInput.value) {
                const newWidth = parseInt(widthInput.value);
                const newHeight = Math.round((sizeInfo.height / sizeInfo.width) * newWidth);
                heightInput.value = newHeight;
            }
            // 如果只修改了高度，自动计算宽度
            else if (heightInput.value && !widthInput.value) {
                const newHeight = parseInt(heightInput.value);
                const newWidth = Math.round((sizeInfo.width / sizeInfo.height) * newHeight);
                widthInput.value = newWidth;
            }
        }

        // 绑定输入框事件
        function bindEvents() {
            const widthInput = document.getElementById('width');
            const heightInput = document.getElementById('height');
            const scaleInput = document.getElementById('scale');
            
            if (widthInput) {
                widthInput.addEventListener('input', updateDimensions);
            }
            if (heightInput) {
                heightInput.addEventListener('input', updateDimensions);
            }
            if (scaleInput) {
                scaleInput.addEventListener('input', updateDimensionsFromScale);
            }
        }

        // 页面加载完成后绑定事件
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', bindEvents);
        } else {
            bindEvents();
        }

        function showStatus(message, type) {
            const status = document.getElementById('status');
            status.textContent = message;
            status.className = `status ${type}`;
        }
    </script>
</body>
</html> 